﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using WebStore.Domain.Entities.Enum;
using WebStore.Domain.Entities.Model;
using WebStore.Web.App.Models.Product;
using WebStore.Web.App.Utility.Attributes;
using WebStore.Web.App.Utility.Other;

namespace WebStore.Web.App.Controllers
{
    public partial class ProductController
    {
        private const int PageSize = 2;

        public ViewResult List(string category, int page = 1)
        {
          
            ViewBag.SelectedCategory = category;
            var model = new ProductListModel
            {
                Products = _entities.Products
                .Include(x=>x.Category)
                .Where(x => (category == null || x.Category.Name.Equals(category))&&!x.IsDeleted)
                .OrderBy(p => p.Id)
                .Skip((page - 1) * PageSize)
                .Take(PageSize)  
                .ToList()
                .Select(x=>Mapper.Map<ProductModel>(x)),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = _entities.Products.Include(x=>x.Category).Count(x => category == null || x.Category.Name.Equals(category))
                },
                Category = category
            };
            return View(model);
        }

        public FileResult ProductPhoto(int id)
        {
            var firstOrDefault = _entities.Products.FirstOrDefault(x => x.Id == id);
            if (firstOrDefault != null&&firstOrDefault.Photo!=null)
                return File(firstOrDefault.Photo, "jpg");
            return null;
        }
    }
}